import type {
  EnergyDataReportInformant,
  EnergyDataReportList,
  LoadListParams,
} from './types'
import { useStatementStore } from '@/store'

export type ReportList = EnergyDataReportList<{
  key: string
  value: string | number
  editable?: boolean
  calculable?: boolean
  calculableKey?: string
  [propName: string]: any
}>

export default function useLoadList(
  request: (params: LoadListParams) => Promise<any>,
  transfer?: (
    data: any,
    config: ReturnType<typeof useStatementStore>
  ) => ReportList[],
) {
  const statementStore = useStatementStore()
  const lists = ref<ReportList[]>([])

  const informant = ref<EnergyDataReportInformant>({
    personInCharge: '',
    informer: '',
    telephone: '',
    fillInDate: '',
  })

  async function load(params: LoadListParams) {
    const { statementFlattenColumns: flattenColumns }
      = statementStore
    const props = flattenColumns.map(v => v.prop)
    return request(params).then(({ data }) => {
      if (!data || data.length === 0) {
        return [
          ...Array(16)
            .fill('')
            .map(() =>
              props.reduce((acc, v) => {
                acc[v] = ''
                return acc
              }, {} as any),
            ),
        ]
      }
      return data
    })
  }

  const defaultTransfer = (
    data: any[],
    store: ReturnType<typeof useStatementStore>,
  ): ReportList[] => {
    const {
      statementFlattenColumns: flattenColumns,
      readonly,
    } = store
    const keys = flattenColumns.map(v => v.prop)
    return data.map((v: any) => {
      return {
        uuid: uuid(),
        informant: {
          personInCharge: v.personInCharge,
          informer: v.informer,
          telephone: v.telephone,
          fillInDate: v.fillInDate,
        },
        data: keys.map(key => ({
          key,
          value: String(v[key] || ''),
          editable: !readonly,
        })),
      }
    })
  }

  function setInformant(v: any) {
    informant.value = {
      personInCharge: v.personInCharge,
      informer: v.informer,
      telephone: v.telephone,
      fillInDate: v.fillInDate,
    }
  }

  async function loadList() {
    const { year, quarter, enterpriseId } = statementStore
    const data = await load({
      year,
      quarter,
      tenantId: enterpriseId,
    })

    // 从list中取填报人信息
    if (data[0]) {
      setInformant(data[0])
    }

    lists.value = transfer
      ? transfer(data, statementStore)
      : defaultTransfer(data, statementStore)
  }

  async function loadPrevList() {
    const { year, quarter, isAnnual, enterpriseId }
      = statementStore
    let y = toValue(year)
    let q = toValue(quarter)
    if (isAnnual) {
      // 年度
      y = Number(y) - 1
    }
    else {
      q = Number(q) - 1
      if (q === 0) {
        y = Number(y) - 1
        q = 4
      }
    }
    const data = await load({
      year: y,
      quarter: q,
      tenantId: enterpriseId,
    })

    // 从list中取填报人信息
    if (data[0]) {
      setInformant(data[0])
    }

    lists.value = transfer
      ? transfer(data, statementStore)
      : defaultTransfer(data, statementStore)
  }

  return {
    lists,
    informant,

    /** 加载并处理年度季度数据 */
    loadList,
    /** 加载并处理上一年度季度数据 */
    loadPrevList,
  }
}
